import 'package:cached_network_image/cached_network_image.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ball_lion/entity/other/resource_entity.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/resources/styles.dart';
import 'package:ball_lion/server/api/other_api.dart';
import 'package:ball_lion/utils/toast_utils.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/widgets/base/wqs_button.dart';
import 'package:ball_lion/widgets/base/wqs_dialog.dart';
import 'package:ball_lion/entity/home/task/task_entity.dart';
import 'package:ball_lion/server/api/king_api.dart';
import 'package:ball_lion/widgets/base/wqs_text.dart';

class PointMarketPage extends StatefulWidget {
  const PointMarketPage({super.key});

  @override
  State<PointMarketPage> createState() => _PointMarketPageState();
}

class _PointMarketPageState extends State<PointMarketPage> {
  List<MarketItem>? entity;
  int point = 0;
  int _page = 1;
  String? rule;
  bool hasRedeem = false;
  EasyRefreshController controller =
      EasyRefreshController(controlFinishLoad: true);

  int get page => _page;
  set page(int value) {
    setState(() {
      _page = value;
    });
  }

  @override
  void initState() {
    refresh();
    super.initState();
  }

  Future refresh() async {
    List<ResourceEntity>? tip = await OtherApi.getAppList("app_res_tips");
    tip?.forEach((element) {
      if (element.button == "point_market_tip") rule = element.content;
    });
    page = 1;
    point = (await KingApi.getTask()).points ?? 0;
    entity = await KingApi.getMarket(page, 15);
    controller.resetFooter();
    setState(() {});
  }

  Future loadMore() async {
    page += 1;
    entity?.addAll(await KingApi.getMarket(page, 15));
    controller.finishLoad(entity!.length < page * 15
        ? IndicatorResult.noMore
        : IndicatorResult.success);
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        Get.back(result: hasRedeem);
        return true;
      },
      child: Scaffold(
        appBar: Styles.appBar(
            backgroundColor: Colours.transparent,
            title: QsText('积分兑换'),
            actions: [
              QsButton(
                onPressed: () {
                  if (rule.hasValue)
                    Get.dialog(QsDialog.single("规则说明", content: rule!));
                },
                text: '规则说明',
                textStyle: const TextStyle(
                    fontSize: 15, fontWeight: FontWeight.normal),
              ).marginOnly(right: 16)
            ]),
        backgroundColor: Colours.scaffoldBg,
        body: EasyRefresh.builder(
            controller: controller,
            footer: Styles.refreshFooter(position: IndicatorPosition.locator),
            onRefresh: refresh,
            onLoad: loadMore,
            childBuilder: (context, physics) {
              return Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 16),
                  child: ListView(physics: physics, children: [
                    myPoint(),
                    Wrap(
                      spacing: 10,
                      runSpacing: 10,
                      children: List.generate(
                          entity?.length ?? 0, (index) => item(entity![index])),
                    ),
                    const FooterLocator()
                  ]));
            }),
      ),
    );
  }

  Widget myPoint() {
    return Styles.card(
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 16),
        margin: const EdgeInsets.symmetric(vertical: 10),
        child: Row(
          children: [
            QsText('我的积分', fontWeight: FontWeight.w500),
            const SizedBox(width: 4),
            QsText("$point", color: Colours.main, fontWeight: FontWeight.w500),
            const Spacer(),
            QsButton(
              onPressed: () => Get.back(result: true),
              text: '获取更多',
              textStyle: const TextStyle(fontSize: 13),
              height: 24,
              width: 60,
              backgroundColor: Colours.main,
              foregroundColor: Colours.white,
              borderRadius: 4,
            )
          ],
        ));
  }

  Widget item(MarketItem data) {
    return Styles.card(
        width: (Get.width - 40) / 2 - 1,
        padding: const EdgeInsets.symmetric(vertical: 16),
        child: Column(
          children: [
            CachedNetworkImage(
                fit: BoxFit.cover,
                width: 94,
                height: 102,
                imageUrl: data.logo ?? "",
                placeholder: (context, url) => Container(),
                errorWidget: (context, url, error) => Container()),
            const SizedBox(height: 12),
            QsText(data.name ?? ""),
            const SizedBox(height: 2),
            QsText("${data.points ?? ""}积分", color: Colours.main, fontSize: 12),
            const SizedBox(height: 10),
            if (data.isTake == 1)
              QsButton(
                onPressed: () async {
                  var check = await Get.dialog(QsDialog.alert("确定要兑换吗"));
                  if (check) {
                    var result = await KingApi.exchange(data.id);
                    if (result == 200) {
                      refresh();
                      Toast.text("兑换成功");
                    }
                    setState(() {
                      hasRedeem = true;
                    });
                  }
                },
                text: '立即兑换',
                textStyle: const TextStyle(fontSize: 13),
                height: 24,
                width: 60,
                backgroundColor: Colours.main,
                foregroundColor: Colours.white,
                borderRadius: 4,
              ),
            if (data.isTake == 0)
              QsButton(
                onPressed: () => Get.back(result: true),
                text: '获取更多',
                textStyle: const TextStyle(fontSize: 13),
                height: 24,
                width: 60,
                backgroundColor: Colours.white,
                foregroundColor: Colours.main,
                borderSide: const BorderSide(color: Colours.main, width: 1),
                borderRadius: 4,
              )
          ],
        ));
  }
}
